import { _decorator, Component, EventTouch, find, Node, UITransform, view } from 'cc';
import { KuGoConfig } from '../../KugoConfig';
import { KugoPiecesType } from '../../KugoConst';
import { ChessPiecesMgr } from './ChessPiecesMgr';
const { ccclass, property } = _decorator;

/**棋盘落子 */
@ccclass('ChessBassDrop')
export class ChessBassDrop extends Component {
    @property(ChessPiecesMgr)
    chessPiecesMgr:ChessPiecesMgr = null


    private _gridSize = KuGoConfig.GridSize
    /**单格宽度 */
    private _rowWidth = 0
    /**单格高度 */
    private _colHeight = 0
    start() {
        this.initTouchEvent()

        let cSize = this.node.getComponent(UITransform).contentSize
        this._rowWidth = cSize.width / this._gridSize
        this._colHeight = cSize.height / this._gridSize
    }

    /**初始化界面触摸 */
    initTouchEvent(){
        let that = this
        this.node.on(Node.EventType.TOUCH_START,function(event: EventTouch){
            return true
        })

        this.node.on(Node.EventType.TOUCH_MOVE,function(event: EventTouch){
            return true
        })

        this.node.on(Node.EventType.TOUCH_END,function(event: EventTouch){
            let pos = that.getTargetPos(event)
            that.dropPos(pos)
            return true
        })
    }


    /**坐标转化 */
    getTargetPos(event){
        let canvas = find("Canvas")
        let cSize = canvas.getComponent(UITransform).contentSize
        //转化为屏幕坐标
        let selfx =  (this.node.position.x + this.node.parent.position.x + cSize.width / 2)
        let selfy =  (this.node.position.y + this.node.parent.position.y + cSize.height / 2 )
        //除getScaleX是因为视图坐标会有缩放 -自己的屏幕坐标 即转换层自己区域坐标
        let x = event.getLocationX()/view.getScaleX() - selfx
        let y = event.getLocationY()/view.getScaleY() - selfy
        return {x:x, y:y}
    }

    /**落子坐标 */
    dropPos(pos:{x:number,y:number}){
        console.log("落子坐标", pos)
        //计算坐标落点
        let dropRow = Math.floor(pos.x/this._rowWidth)
        let dropCol = Math.floor(pos.y/this._colHeight)

        let xDrop = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        console.log("落子 X:", dropRow, xDrop[dropRow], "Y:", (dropCol + 1))

        this.chessPiecesMgr.drop(pos)
    }
}


